package se.vgregion.velocity.hook.rss.util;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/*
 * This util allows changes in the RSSTool without restarting Liferay (since bean signature of RSSTool bean isn't changed). 
 * */
public class RSSToolUtil {

	public static List<SyndEntry> readFeed(String urlStr) {
		
		XmlReader reader = null;
		
		ArrayList<SyndEntry> emptyList = new ArrayList<SyndEntry>();
		List<SyndEntry> feedEntries = new ArrayList<SyndEntry>(emptyList);
	 
		try {
			
			URL url  = new URL(urlStr);
	 
			reader = new XmlReader(url);
			SyndFeed feed = new SyndFeedInput().build(reader);
			
			feedEntries = feed.getEntries();
		} catch (IOException e) {
//			_log.error(e, e);
		} catch (IllegalArgumentException e) {
//			_log.error(e, e);
		} catch (FeedException e) {
//			_log.error(e, e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
//					_log.error(e, e);
				}
			}
		}
		return feedEntries;
	}
	
	public static List<SyndEntry> readFeed(String urlStr, int maxEntriesCount) {
		List<SyndEntry> feedEntries = readFeed(urlStr);
		
		if(feedEntries.size() > maxEntriesCount) {
			feedEntries = feedEntries.subList(0, maxEntriesCount);	
		}
		return feedEntries;
	}
	
//	private static Log _log = LogFactoryUtil.getLog(RSSToolUtil.class);
}
